package com.boarsoft.boar.deploy.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;

import com.boarsoft.agent.AgentService;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.BaseConfig;
import com.boarsoft.boar.deploy.bean.BuildInstParam;
import com.boarsoft.common.Util;
import com.boarsoft.flow.core.bean.ProcessHandler;
import com.boarsoft.rpc.core.RpcContext;

/**
 * 此Handler会调用位于目标服务器的agentX，备份指定的目录或文件<br>
 * 
 * @author Mac_J
 *
 */
public class BackupFilePH implements ProcessHandler {
	private static Logger log = LoggerFactory.getLogger(BackupFilePH.class);

	@Autowired
	@Lazy
	@Qualifier("agentX")
	private AgentService agentX;

	private String shell;

	private String to;

	@Override
	public Object process(String entry, Object data, Throwable throwable) throws Throwable {
		BuildInstParam p = (BuildInstParam) data;
		String axa = new StringBuilder().append(p.getIp()).append(":")//
				.append(BaseConfig.AGENTX_PORT).toString();
		String path = p.getTargetPath();
		String dest = to;
		if (Util.strIsEmpty(to)) {
			dest = new StringBuilder("./backup/").append(p.getCode())//
					.append("-").append(p.getVersion()).append("/")//
					.append(Util.date2str(Util.STDDTF2)).toString();
		} else {
			// TODO 处理参数变量？
		}
		log.info("Ask agentX {} backup file path {} to {}", axa, path, dest);
		RpcContext.specify2(axa);
		try {
			ReplyInfo<Object> ro = null;
			if (Util.strIsEmpty(shell)) {
				ro = agentX.copy2(path, dest);
			} else {
				ro = agentX.executeCmd(shell, new String[] { path, to }, p.getTaskId());
			}
			if (ro.isSuccess()) {
				log.info("AgentX {} backup file path {} to {} sucessfully", //
						axa, path, dest);
				return data;
			}
			throw new Exception(new StringBuilder("AgentX ").append(axa)//
					.append(" backup file path ").append(path)//
					.append(" to ").append(dest)//
					.append(" failed, reason: ")//
					.append(ro.getData()).toString());
		} finally {
			RpcContext.specify2(null);
		}
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public String getShell() {
		return shell;
	}

	public void setShell(String shell) {
		this.shell = shell;
	}
}